from rest_framework.views import APIView
from luffyapi.libs.geetest import GeetestLib
from rest_framework.response import Response

# 放置极验生成的id和key，将来这两行代码要放到settings下的配置文件中
pc_geetest_id = "08faa04afc548993b1c79336d1671cc8"
pc_geetest_key = "42e17e57bb181dfbe02d6faaeb157cf7"
class CaptchaAPIView(APIView):
    def get(self,request):
        """生成行为验证流水号"""
        user_id = 'test'
        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        status = gt.pre_process(user_id)
        # request.session[gt.GT_STATUS_SESSION_KEY] = status
        # request.session["user_id"] = user_id
        response_str = gt.get_response_str()
        return Response(response_str)
    def post(self,request):
        """获取行为验证的结果"""
        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        challenge = request.POST.get(gt.FN_CHALLENGE, '')  # 极验的流水号
        validate = request.POST.get(gt.FN_VALIDATE, '') # 验证结果
        seccode = request.POST.get(gt.FN_SECCODE, '')  # 返回的响应状态码
        # status = request.session[gt.GT_STATUS_SESSION_KEY]
        # user_id = request.session["user_id"]
        # if status:
        #     result = gt.success_validate(challenge, validate, seccode, user_id)
        # else:
        result = gt.failback_validate(challenge, validate, seccode)
        result = {"status":"success"} if result else {"status":"fail"}
        return Response(result)


